import { getList, getLogDetail, requestPieData } from '@/api/logManager'
import dayjs from 'dayjs'
import { ColumnProps, Space, Tag, Message, Modal } from '@kedacom/react-next'
import { useEffect, useState } from 'react'
import { FilterDataProps, PieDataProps, TableListProps } from '../interface'
import { transTableList } from '../translatorLog'
import { defaultFilterData, FilterParamsProps } from '../context'
import { DigestAuth } from '@/utils/encryption/digestAuth'

const useIndexHook = (type: string) => {
	const rowKey = 'id'
	const [data, setData] = useState<TableListProps[]>([])
	const [pieLogLevelData, setPieLogLevelData] = useState<any[]>([])
	const [pieBehaviorData, setPieBehaviorData] = useState<any[]>([])
	const [show, setShow] = useState<boolean>(false)
	const [detailData, setDetailData] = useState<TableListProps>()
	const [passwordShow, setPasswordShow] = useState<boolean>(false)
	const [exportId, setExportId] = useState<string>('')
	const [password, setPassword] = useState<string>('')
	const [showPie, setShowPie] = useState(false)
	//分页【page/size改变触发table更新】
	const [params, setParams] = useState<FilterParamsProps>(defaultFilterData)
	const [filterData, setFilterData] = useState<FilterDataProps>({
		detail: defaultFilterData.detail, //账号/姓名/邮箱/入会号码
		accountName: defaultFilterData.accountName, //用户 名称
		subjectName: defaultFilterData.subjectName, //事件主体
		nameCodeLevel: defaultFilterData.nameCodeLevel, //名称编码密级
		logRiskLevel: defaultFilterData.logRiskLevel, //日志风险级别
		type: defaultFilterData.type, //操作类型
		startDate: defaultFilterData.startDate, //开始时间
		endDate: defaultFilterData.endDate, //结束时间
	})
	const [total, setTotal] = useState<number>(0)
	const [logLevelSeries, setLogLevelSeries] = useState<object>({
		title: '注：根据日志风险级别分类',
		center: ['40%', '50%'],
		radius: ['25%', '51%'],
	})
	const [behaviorSeries, setBehaviorSeries] = useState<object>({
		title: '注：根据行为类别分类',
		center: ['40%', '50%'],
		radius: '50%',
	})
	const columns: ColumnProps<TableListProps>[] = [
		{
			title: '日志ID',
			width: 160,
			dataKey: 'id',
			render(rowData, text, index) {
				return <span title={text}>{text}</span>
			},
		},
		{
			title: '事件主体',
			width: 100,
			dataKey: 'subjectName',
			render(rowData, text, index) {
				return <span title={text}>{text}</span>
			},
		},
		{
			title: '事件客体',
			width: 130,
			dataKey: 'objectName',
			render(rowData, text, index) {
				return <span title={text}>{text}</span>
			},
		},
		{
			title: '事件内容',
			minWidth: 200,
			dataKey: 'details',
			render(rowData, text, index) {
				text = text.replace('“usbKey” 设置为“”', '操作：usbKey解绑')
				text = text.replace('“usbKey” 设置为', '操作：usbKey绑定为')
				return <span title={text}>{text.split('，原因').shift()}</span>
			},
		},
		{
			title: '事件发生时间',
			width: 160,
			dataKey: 'time',
			render(rowData, text, index) {
				return (
					<span title={dayjs(text).format('YYYY-MM-DD HH:mm:ss')}>
						{dayjs(text).format('YYYY-MM-DD HH:mm:ss')}
					</span>
				)
			},
		},
		{
			title: '事件风险等级',
			width: 100,
			dataKey: 'level',
			render(rowData, value, index) {
				let levelList = ['紧急', '警报', '关键', '错误', '警告', '通知', '信息', '调试']
				return <span>{levelList[value]}</span>
			},
		},
		{
			title: '事件种类',
			width: 100,
			dataKey: 'type',
			render(rowData, value, index) {
				let _value = ''
				if (value === 'm') {
					_value = '管理员操作日志'
				} else if (value === 'a') {
					_value = '用户操作日志'
				} else {
					_value = '其他日志'
				}
				return <span title={_value}>{_value}</span>
			},
		},
		{
			title: '行为类别',
			width: 100,
			dataKey: 'behaviourType',
			render(rowData, value, index) {
				let typeList = ['违规行为', '异常行为', '一般行为']
				return <span>{typeList[value - 1]}</span>
			},
		},
		{
			title: '操作',
			dataKey: '__operator',
			width: 80,
			minWidth: 80,
			render(rowData: TableListProps, value: any, index: any) {
				return (
					<Space space={10}>
						<Tag onClick={() => toDetail(rowData)}>详情</Tag>
						{/* <Tag onClick={() => exportApprove(rowData)}>导出</Tag> */}
						<Tag onClick={() => exportApprove(rowData)}>导出</Tag>
					</Space>
				)
			},
		},
	]
	useEffect(() => {
		getTableList()
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [params])
	/**点击回车或搜索图标时 */
	// const onFilterSearch = (filterDataObj: FilterDataProps) => {
	// 	getTableList(pager, filterDataObj)
	// }
	//获取表格数据
	const getTableList = () => {
		let m = Message.loading('正在加载，请稍候...')
		let dataJson = {
			type: params?.type,
			detail: params?.detail,
			object_name: params?.nameCodeLevel, // 日志客体名称
			subject_name: params?.accountName, // 主体名称
			level: params?.logRiskLevel, //事件风险级别
			end_time: params?.endDate,
			start_time: params?.startDate,
			page: params.page,
			size: params.size,
			_o: encodeURIComponent('操作日志'),
		}
		getList(dataJson, type)
			.then((res) => {
				m.hide()
				let list = transTableList(res.list ?? [])
				setData(list)
				setTotal(res.total ?? 0)
				if (list.length === 0 && params.page !== 1) {
					setParams({ ...params, page: 1 })
				}
			})
			.catch((res) => {
				m.hide()
			})
	}

	//分页改变时 setPager分页改变 会自动 getTableList
	const onPageChange = (pageIndex: number, pageSize: number) => {
		setParams({ ...filterData, page: pageIndex, size: pageSize })
	}
	/**点击详情弹出框 */
	const toDetail = (record: TableListProps) => {
		// 请求数据
		let params = {
			id: record.id || '',
		}
		getLogDetail(params, type)
			.then((res) => {
				setDetailData(res.data)
				showDetail(true)
			})
			.catch((res) => {})
	}
	const showDetail = (value: boolean) => {
		setShow(value)
	}
	const toPieData = (obj: PieDataProps[]) => {
		let pieData: object[] = []
		pieData.push({ name: '警告', value: obj[0].alarm || null })
		pieData.push({ name: '警报', value: obj[0].alert || null })
		pieData.push({ name: '关键', value: obj[0].crux || null })
		pieData.push({ name: '调试', value: obj[0].debug || null })
		pieData.push({ name: '错误', value: obj[0].error || null })
		pieData.push({ name: '信息', value: obj[0].info || null })
		pieData.push({ name: '通知', value: obj[0].notice || null })
		pieData.push({ name: '紧急', value: obj[0].urgent || null })
		return pieData
	}
	const changeBehavior = (object: PieDataProps[]) => {
		let pieBehaviorData: object[] = []
		pieBehaviorData.push({ name: '违规行为', value: object[0].violation || null })
		pieBehaviorData.push({ name: '异常行为', value: object[0].abnormal || null })
		pieBehaviorData.push({ name: '一般行为', value: object[0].normal || null })
		return pieBehaviorData
	}
	const showPieChartToggle = () => {
		setShowPie(!showPie)
	}
	const showPieChart = () => {
		let dataJson = {
			type: params?.type,
			detail: params?.detail,
			object_name: params?.nameCodeLevel, // 日志客体名称
			subject_name: params?.accountName, // 主体名称
			level: params?.logRiskLevel, //事件风险级别
			end_time: params?.endDate,
			start_time: params?.startDate,
			page: params.page,
			size: params.size,
		}
		getPieData(dataJson)
	}
	/**请求日志风险级别饼图，行为类别饼图 */
	const getPieData = (dataJson: object) => {
		requestPieData(dataJson, type)
			.then((res) => {
				setPieBehaviorData(changeBehavior([res.data.behaviour_type]))
				setPieLogLevelData(toPieData([res.data.level]))
				setShowPie(!showPie)
			})
			.catch((res) => {})
	}
	const showPasswordDialog = (value: boolean) => {
		setPasswordShow(value)
		if (value) {
			setPassword('')
		}
	}
	const passwordConfirm = () => {
		/** 导出数据 浏览器下载 */
		/** 通过toast提示 */
		if (!password) {
			let m = Modal.alert({
				content: <div>请输入加密密码</div>,
				onOk: () => {
					m.hide()
				},
				onCancel: () => {
					m.hide()
				},
			})
			return
		}
		let data = DigestAuth.makeSM4Encrypt(password)
		console.log(data)
		if (exportId) {
			window.location.href = `/sas/logs/export/${type}/?logid=${exportId}&c=${data.ciphertext}&k=${data.mkey}`
		} else {
			window.location.href = window.location.href = `/sas/logs/export/${type}?detail=${params.detail}&end_time=${
				params.endDate ? encodeURIComponent(params.endDate) : null
			}&level=${params.logRiskLevel}&start_time=${
				params.startDate ? encodeURIComponent(params.startDate) : null
			}&subject_name=${params.accountName}&type=${params.type}&object_name=${params.nameCodeLevel}&c=${
				data.ciphertext
			}&k=${data.mkey}`
		}
		showPasswordDialog(false)
		setExportId('')
	}
	/**导出 */
	const exportApprove = (record: TableListProps) => {
		showPasswordDialog(true)
		setExportId(record.id as string)
	}

	return {
		/**点击回车或搜索图标时 */
		// onFilterSearch,
		columns,
		/**唯一标识字段 */
		rowKey,
		params,
		setParams,
		filterData,
		setFilterData,
		total,
		/**表格数据 */
		data,
		/**展示弹出框 */
		show,
		onPageChange,
		showDetail,
		detailData,
		exportApprove,
		passwordShow,
		password,
		setPassword,
		showPasswordDialog,
		passwordConfirm,
		showPieChart,
		showPieChartToggle,
		showPie,
		pieLogLevelData,
		pieBehaviorData,
		behaviorSeries,
		logLevelSeries,
	}
}
export default useIndexHook
